const express = require('express')
const router = express.Router()
const User = require('../models/User')
const db = require('../config/database')

// 获取所有用户（分页）
router.get('/', async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1
    const limit = parseInt(req.query.limit) || 10
    const search = req.query.search || ''
    const offset = (page - 1) * limit

    console.log('📋 获取用户列表请求参数:', { page, limit, search, offset })

    // 构建搜索条件
    let whereClause = ''
    let searchParams = []

    if (search.trim()) {
      whereClause = 'WHERE username LIKE ? OR email LIKE ? OR nickname LIKE ?'
      const searchPattern = `%${search}%`
      searchParams = [searchPattern, searchPattern, searchPattern]
    }

    // 获取总数
    const countQuery = `SELECT COUNT(*) as total FROM users ${whereClause}`
    console.log('📊 统计查询:', countQuery, searchParams)
    const countResult = await db.query(countQuery, searchParams)
    const total = countResult[0].total

    // 获取用户列表 - 使用正确的数据库列名
    const usersQuery = `
      SELECT 
        id, username, email, nickname, 
        avatar_url as avatar,
        level, coins as balance, 
        CASE 
          WHEN is_vip = 1 AND vip_expire_date > NOW() THEN 'yearly'
          ELSE 'none'
        END as vipStatus,
        status, role, 
        created_at as createdAt, 
        last_login_time as lastLoginTime
      FROM users 
      ${whereClause}
      ORDER BY created_at DESC 
      LIMIT ${limit} OFFSET ${offset}
    `

    console.log('📋 用户查询:', usersQuery, searchParams)
    const users = await db.query(usersQuery, searchParams)

    console.log('✅ 查询成功，返回用户数:', users.length)

    res.json({
      success: true,
      data: {
        users,
        pagination: {
          page,
          limit,
          total,
          pages: Math.ceil(total / limit)
        }
      }
    })
  } catch (error) {
    console.error('❌ 获取用户列表失败:', error)
    res.status(500).json({
      success: false,
      message: '获取用户列表失败',
      error: error.message
    })
  }
})

// 获取用户统计信息
router.get('/stats', async (req, res) => {
  try {
    console.log('📊 获取用户统计信息...')

    // 获取总用户数
    const totalResult = await db.query('SELECT COUNT(*) as total FROM users')
    const totalUsers = totalResult[0].total

    // 获取活跃用户数（假设最近30天登录为活跃）
    const activeResult = await db.query(`
      SELECT COUNT(*) as active 
      FROM users 
      WHERE last_login_time >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    `)
    const activeUsers = activeResult[0].active

    // 获取VIP用户数
    const vipResult = await db.query(`
      SELECT COUNT(*) as vip 
      FROM users 
      WHERE is_vip = 1 AND vip_expire_date > NOW()
    `)
    const vipUsers = vipResult[0].vip

    // 获取今日新增用户数
    const todayResult = await db.query(`
      SELECT COUNT(*) as today 
      FROM users 
      WHERE DATE(created_at) = CURDATE()
    `)
    const newUsersToday = todayResult[0].today

    // 获取昨日新增用户数用于计算增长率
    const yesterdayResult = await db.query(`
      SELECT COUNT(*) as yesterday 
      FROM users 
      WHERE DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)
    `)
    const newUsersYesterday = yesterdayResult[0].yesterday

    // 计算真实增长率
    // 获取前一天总用户数（昨天之前的用户数）
    const previousTotalResult = await db.query(`
      SELECT COUNT(*) as total 
      FROM users 
      WHERE DATE(created_at) < CURDATE()
    `)
    const previousTotal = previousTotalResult[0].total

    // 获取前30天活跃用户数（31-60天前登录的用户）
    const previousActiveResult = await db.query(`
      SELECT COUNT(*) as active 
      FROM users 
      WHERE last_login_time >= DATE_SUB(NOW(), INTERVAL 60 DAY)
      AND last_login_time < DATE_SUB(NOW(), INTERVAL 30 DAY)
    `)
    const previousActiveUsers = previousActiveResult[0].active

    // 获取前一天VIP用户数
    const previousVipResult = await db.query(`
      SELECT COUNT(*) as vip 
      FROM users 
      WHERE is_vip = 1 AND vip_expire_date > DATE_SUB(NOW(), INTERVAL 1 DAY)
      AND (created_at < CURDATE() OR vip_expire_date <= NOW())
    `)
    const previousVipUsers = previousVipResult[0].vip

    // 计算真实增长率
    const totalUsersGrowth =
      previousTotal > 0
        ? Math.round(((totalUsers - previousTotal) / previousTotal) * 100)
        : totalUsers > 0
        ? 100
        : 0

    const activeUsersGrowth =
      previousActiveUsers > 0
        ? Math.round(
            ((activeUsers - previousActiveUsers) / previousActiveUsers) * 100
          )
        : activeUsers > 0
        ? 100
        : 0

    const vipUsersGrowth =
      previousVipUsers > 0
        ? Math.round(((vipUsers - previousVipUsers) / previousVipUsers) * 100)
        : vipUsers > 0
        ? 100
        : 0

    const newUsersTodayGrowth =
      newUsersYesterday > 0
        ? Math.round(
            ((newUsersToday - newUsersYesterday) / newUsersYesterday) * 100
          )
        : newUsersToday > 0
        ? 100
        : 0

    const stats = {
      totalUsers,
      totalUsersGrowth,
      activeUsers,
      activeUsersGrowth,
      vipUsers,
      vipUsersGrowth,
      newUsersToday,
      newUsersTodayGrowth
    }

    console.log('✅ 统计信息获取成功:', stats)

    res.json({
      success: true,
      data: stats
    })
  } catch (error) {
    console.error('❌ 获取用户统计失败:', error)
    res.status(500).json({
      success: false,
      message: '获取用户统计失败',
      error: error.message
    })
  }
})

// 创建新用户
router.post('/', async (req, res) => {
  try {
    console.log('🆕 创建用户请求:', req.body)

    const {
      email,
      nickname,
      password,
      role = 'user',
      status = 'active',
      vipStatus = 'none',
      level = 1,
      balance = 0,
      avatar
    } = req.body

    // 验证必填字段
    if (!email || !nickname || !password) {
      return res.status(400).json({
        success: false,
        message: '邮箱、昵称和密码为必填项'
      })
    }

    // 检查邮箱是否已存在
    const existingUser = await db.query(
      'SELECT id FROM users WHERE email = ?',
      [email]
    )
    if (existingUser.length > 0) {
      return res.status(400).json({
        success: false,
        message: '该邮箱已被使用'
      })
    }

    // 密码加密
    const bcrypt = require('bcrypt')
    const saltRounds = 10
    const passwordHash = await bcrypt.hash(password, saltRounds)

    // 处理VIP状态
    let isVip = false
    let vipExpireDate = null
    if (vipStatus === 'monthly') {
      isVip = true
      vipExpireDate = new Date()
      vipExpireDate.setMonth(vipExpireDate.getMonth() + 1)
    } else if (vipStatus === 'yearly') {
      isVip = true
      vipExpireDate = new Date()
      vipExpireDate.setFullYear(vipExpireDate.getFullYear() + 1)
    }

    // 生成username，如果没有提供的话使用nickname
    const username = nickname || email.split('@')[0]

    // 创建用户
    const insertResult = await db.query(
      `
      INSERT INTO users (
        username, email, nickname, password_hash, role, status, level, 
        coins, is_vip, vip_expire_date, avatar_url, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    `,
      [
        username,
        email,
        nickname,
        passwordHash,
        role,
        status,
        level,
        balance,
        isVip,
        vipExpireDate,
        avatar || null
      ]
    )

    const userId = insertResult.insertId

    // 返回创建的用户信息（不包含密码）
    const newUser = {
      id: userId.toString(),
      email,
      nickname,
      role,
      status,
      level,
      balance,
      vipStatus,
      avatar: avatar || null,
      createdAt: new Date()
    }

    console.log('✅ 用户创建成功:', newUser)

    res.status(201).json({
      success: true,
      message: '用户创建成功',
      data: { user: newUser }
    })
  } catch (error) {
    console.error('❌ 创建用户失败:', error)
    res.status(500).json({
      success: false,
      message: '创建用户失败',
      error: error.message
    })
  }
})

// 根据ID获取用户
router.get('/:id', async (req, res) => {
  try {
    const user = await User.findById(req.params.id)
    if (!user) {
      return res.status(404).json({ error: '用户不存在' })
    }

    // 转换数据格式
    const userData = {
      id: user.id.toString(),
      email: user.email,
      nickname: user.nickname || user.username,
      username: user.username,
      avatar: user.avatar_url,
      level: user.level || 1,
      vipStatus: user.is_vip ? 'yearly' : 'none',
      vipExpireDate: user.vip_expire_date,
      balance: user.coins || 0,
      role: user.role || 'user',
      status: user.status || 'active',
      createdAt: user.created_at,
      lastLoginTime: user.last_login_time
    }

    res.json(userData)
  } catch (error) {
    console.error('获取用户信息失败:', error)
    res.status(500).json({ error: '获取用户信息失败' })
  }
})

// 更新用户信息
router.put('/:id', async (req, res) => {
  try {
    console.log('📝 更新用户请求:', req.params.id, req.body)

    const updates = {}

    // 映射前端字段到数据库字段
    if (req.body.balance !== undefined) {
      updates.coins = req.body.balance
    }
    if (req.body.vipStatus !== undefined) {
      updates.is_vip = req.body.vipStatus !== 'none'
      if (req.body.vipStatus === 'monthly') {
        const expireDate = new Date()
        expireDate.setMonth(expireDate.getMonth() + 1)
        updates.vip_expire_date = expireDate
      } else if (req.body.vipStatus === 'yearly') {
        const expireDate = new Date()
        expireDate.setFullYear(expireDate.getFullYear() + 1)
        updates.vip_expire_date = expireDate
      } else {
        updates.vip_expire_date = null
      }
    }
    if (req.body.status !== undefined) {
      updates.status = req.body.status
    }
    if (req.body.role !== undefined) {
      updates.role = req.body.role
    }
    if (req.body.nickname !== undefined) {
      updates.nickname = req.body.nickname
    }
    if (req.body.level !== undefined) {
      updates.level = req.body.level
    }

    // 处理密码更新 - 特殊处理
    if (req.body.password !== undefined) {
      console.log('🔐 正在更新密码...')
      const bcrypt = require('bcrypt')
      const saltRounds = 10
      updates.password_hash = await bcrypt.hash(req.body.password, saltRounds)
    }

    console.log('📝 最终更新数据:', updates)

    // 如果包含密码更新，需要特殊处理
    if (updates.password_hash) {
      // 直接使用数据库查询来更新密码
      const fields = []
      const values = []

      Object.keys(updates).forEach(key => {
        if (updates[key] !== undefined) {
          fields.push(`${key} = ?`)
          values.push(updates[key])
        }
      })

      values.push(req.params.id)

      await db.query(
        `UPDATE users SET ${fields.join(
          ', '
        )}, updated_at = NOW() WHERE id = ?`,
        values
      )

      console.log('✅ 密码更新成功')
      res.json({ success: true, message: '用户信息更新成功' })
    } else {
      // 常规更新
      const updatedUser = await User.updateById(req.params.id, updates)
      res.json({ success: true, user: updatedUser })
    }
  } catch (error) {
    console.error('❌ 更新用户信息失败:', error)
    res.status(500).json({
      success: false,
      error: '更新用户信息失败',
      message: error.message
    })
  }
})

// 删除用户
router.delete('/:id', async (req, res) => {
  try {
    await db.query('DELETE FROM users WHERE id = ?', [req.params.id])
    res.json({ success: true })
  } catch (error) {
    console.error('删除用户失败:', error)
    res.status(500).json({ error: '删除用户失败' })
  }
})

// 批量更新用户
router.put('/batch', async (req, res) => {
  try {
    const { userIds, updates } = req.body

    if (!userIds || !Array.isArray(userIds) || userIds.length === 0) {
      return res.status(400).json({ error: '用户ID列表不能为空' })
    }

    // 为每个用户执行更新
    for (const userId of userIds) {
      const dbUpdates = {}

      if (updates.balance !== undefined) {
        dbUpdates.coins = updates.balance
      }
      if (updates.vipStatus !== undefined) {
        dbUpdates.is_vip = updates.vipStatus !== 'none'
      }
      if (updates.status !== undefined) {
        dbUpdates.status = updates.status
      }
      if (updates.role !== undefined) {
        dbUpdates.role = updates.role
      }

      await User.updateById(userId, dbUpdates)
    }

    res.json({ success: true })
  } catch (error) {
    console.error('批量更新用户失败:', error)
    res.status(500).json({ error: '批量更新用户失败' })
  }
})

// 执行用户操作
router.post('/:id/actions', async (req, res) => {
  try {
    const { action, operatorId, operatorName } = req.body
    const userId = req.params.id

    // 根据操作类型执行相应的数据库更新
    switch (action.type) {
      case 'ban':
        await User.updateById(userId, {
          status: 'banned',
          ban_reason: action.reason
        })
        break

      case 'unban':
        await User.updateById(userId, {
          status: 'active',
          ban_reason: null
        })
        break

      case 'suspend':
        await User.updateById(userId, {
          status: 'suspended'
        })
        break

      case 'activate':
        await User.updateById(userId, {
          status: 'active'
        })
        break

      case 'recharge':
        const user = await User.findById(userId)
        const newBalance = (user.coins || 0) + action.amount
        await User.updateById(userId, { coins: newBalance })
        break

      case 'deduct':
        const userForDeduct = await User.findById(userId)
        const balanceAfterDeduct = Math.max(
          0,
          (userForDeduct.coins || 0) - action.amount
        )
        await User.updateById(userId, { coins: balanceAfterDeduct })
        break

      case 'grant_vip':
        const vipExpireDate = new Date()
        if (action.vipType === 'monthly') {
          vipExpireDate.setMonth(vipExpireDate.getMonth() + 1)
        } else {
          vipExpireDate.setFullYear(vipExpireDate.getFullYear() + 1)
        }
        await User.updateById(userId, {
          is_vip: true,
          vip_expire_date: vipExpireDate
        })
        break

      case 'revoke_vip':
        await User.updateById(userId, {
          is_vip: false,
          vip_expire_date: null
        })
        break

      default:
        return res.status(400).json({ error: '不支持的操作类型' })
    }

    res.json({ success: true })
  } catch (error) {
    console.error('执行用户操作失败:', error)
    res.status(500).json({ error: '执行用户操作失败' })
  }
})

// 搜索用户
router.get('/search', async (req, res) => {
  try {
    const { q, status, vipStatus, role } = req.query

    let whereClause = 'WHERE 1=1'
    const queryParams = []

    if (q) {
      whereClause += ' AND (username LIKE ? OR email LIKE ? OR nickname LIKE ?)'
      queryParams.push(`%${q}%`, `%${q}%`, `%${q}%`)
    }

    if (status) {
      whereClause += ' AND status = ?'
      queryParams.push(status)
    }

    if (vipStatus) {
      if (vipStatus === 'none') {
        whereClause += ' AND (is_vip = false OR is_vip IS NULL)'
      } else {
        whereClause += ' AND is_vip = true'
      }
    }

    if (role) {
      whereClause += ' AND role = ?'
      queryParams.push(role)
    }

    const users = await db.query(
      `SELECT id, username, email, nickname, avatar_url, is_vip, coins, role, status, created_at 
       FROM users ${whereClause} 
       ORDER BY created_at DESC 
       LIMIT 50`,
      queryParams
    )

    const formattedUsers = users.map(user => ({
      id: user.id.toString(),
      email: user.email,
      nickname: user.nickname || user.username,
      username: user.username,
      avatar: user.avatar_url,
      vipStatus: user.is_vip ? 'yearly' : 'none',
      balance: user.coins || 0,
      role: user.role || 'user',
      status: user.status || 'active',
      createdAt: user.created_at
    }))

    res.json({ users: formattedUsers })
  } catch (error) {
    console.error('搜索用户失败:', error)
    res.status(500).json({ error: '搜索用户失败' })
  }
})

// 导出用户数据
router.get('/export', async (req, res) => {
  try {
    const format = req.query.format || 'csv'

    const users = await db.query(`
      SELECT id, username, email, nickname, is_vip, coins, role, status, created_at
      FROM users 
      ORDER BY created_at DESC
    `)

    if (format === 'csv') {
      const csvHeaders = 'ID,用户名,邮箱,昵称,VIP状态,余额,角色,状态,注册时间\n'
      const csvData = users
        .map(
          user =>
            `${user.id},"${user.username}","${user.email}","${
              user.nickname || ''
            }","${user.is_vip ? 'VIP' : '普通'}",${user.coins || 0},"${
              user.role || 'user'
            }","${user.status || 'active'}","${user.created_at}"`
        )
        .join('\n')

      res.setHeader('Content-Type', 'text/csv; charset=utf-8')
      res.setHeader('Content-Disposition', 'attachment; filename="users.csv"')
      res.send('\ufeff' + csvHeaders + csvData) // 添加BOM以支持Excel中文显示
    } else {
      res.status(400).json({ error: '不支持的导出格式' })
    }
  } catch (error) {
    console.error('导出用户数据失败:', error)
    res.status(500).json({ error: '导出用户数据失败' })
  }
})

module.exports = router
